// 登录页面处理

// express框架
var express = require('express');
var router = express.Router();
const cors = require('cors');
const jwt = require('jsonwebtoken')

const app = express()
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 日志：
const computingLog = require('../../middlewares/computingLog')
// SQUserModel数据库属性
const SQUserModel = require('../../Models/UserModel')

// 加密字符串：
const { secret } = require('../../config/config')

// 加密密码依赖：md5
const md5 = require('md5')


// 登录处理：
router.post('/login', computingLog, function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*'); // 或指定为 'http://localhost:8080'
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

  let { username, password } = req.body
  SQUserModel.findOne({ username: username, password: md5(req.body.password) }).then((data) => {
    if (!data) {
      return res.json({
        code: '2001',
        msg: '账号或密码错误',
        data: null
      })
    } else {
      // 向数据库中存储session
      if (!req.session.username && !req.session.id) {
        req.session.username = data.username
        req.session.id = data._id
      }
      // 定义token
      let token = jwt.sign(
        {
          username: data.username,
          id: data._id
        },
        secret,
        {
          expiresIn: 60 * 60 * 24 * 7
        }
      )

      res.json({
        code: '0000',
        msg: '登录成功',
        data: token
      })
    }
  }).catch((err) => {
    console.log(err);

    res.status(500).json({
      code: '2002',
      msg: '登录失败，请稍后再试',
      data: null
    })
  })
})

// 退出登录处理：
router.post('/logout', computingLog, (req, res) => {
  req.session.destroy(() => {
    res.json({
      code: '0000',
      msg: '删除成功',
      data: ''
    })
  })
})

// 注册处理
router.post('/reg', computingLog, (req, res, next) => {
  SQUserModel.create({ ...req.body, password: md5(req.body.password) }).then((data) => {
    res.json({
      code: '0000',
      msg: '注册成功',
      data: data
    })
    console.log(data);

  }).catch(() => {
    res.status(500).json({
      code: '2003',
      msg: '注册失败',
      data: null
    })
  })
})


module.exports = router;
